// 详情
var PPurchaseDetail = {
    uList: '/pPurchaseDetail/list'
    , uRelative: '/tticar/relativeSku'
    , uDelivery: '/tticar/goodsOrder/deliverySubmit'
    , orderStatus: 0
    , unitArr: []
    , purchaseId: 0,
    isDg: 0,
    editIndex: -1,
    winThat: undefined,
    dgType: undefined,
};

$.extend($.fn.datagrid.defaults.editors, {
    house: {
        init: function (container, options) {
            return $('<div style="text-align: center">编辑</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            var rows = PPurchaseDetail.dtable.datagrid("getRows");
            var house = rows[PPurchaseDetail.editIndex].house;
            return house;
        },
        setValue: function (target, value) {
        },
        resize: function (target, width) {
            $(target).click(function () {
                PPurchaseDetail.isDg = 1;
                var rows = PPurchaseDetail.dtable.datagrid("getRows");
                var skuId = rows[PPurchaseDetail.editIndex].skuId;
                var house = rows[PPurchaseDetail.editIndex].house;
                var href = "/wWearhouse/treeGrid?skuId=" + skuId + "&house=" + house + "&type=0";//type 0出库 1入库
               
                var $dg = $yd.win.create('仓库/库位/批次', href);
                $dg.width = "450px;";
                $dg.height = "520px;";
                $dg.open(function (that, $win) {
                    PPurchaseDetail.winThat = that;
                    PPurchaseDetail.dgType = "house";
                }, function (that, $win) {
                    PPurchaseDetail.saveDgHouse();
                }, function () {
                    if (PPurchaseDetail.editIndex > -1) {
                        PPurchaseDetail.dtable.datagrid('endEdit', PPurchaseDetail.editIndex);
                    }
                    PPurchaseDetail.editIndex = -1;
                    PPurchaseDetail.isDg = 0;
                    PPurchaseDetail.winThat = undefined;
                    PPurchaseDetail.dgType = undefined;
                });
            });

            $(target)._outerWidth(width);
        }
    }
});

PPurchaseDetail.saveDgHouse = function () {
    var data = KW.getResult();
    var wearhouseId = "";
    var positionId = "";
    if (!PPurchaseDetail.isEmpty(data)) {
        var arr = data.split("_");
        wearhouseId = arr[0];
        positionId = arr[2];
    }
    PPurchaseDetail.dtable.datagrid('updateRow', {
        index: PPurchaseDetail.editIndex,
        row: {
            house: data,
            wearhouseId: wearhouseId,
            positionId: positionId
        }
    });

    PPurchaseDetail.winThat.close();
    PPurchaseDetail.isDg = 0;
    PPurchaseDetail.winThat = undefined;
    PPurchaseDetail.dgType = undefined;
};


PPurchaseDetail.dg = function () {


    PPurchaseDetail.dtable.datagrid({
        url: "/tticar/goodsOrder/list/goodsTmp?orderId=" + PPurchaseDetail.orderCode,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        nowrap:false,
        onClickRow : function (rowIndex,rowData) {
            $(this).datagrid('unselectRow', rowIndex);
        },
        columns: [[
            // {field: 'wearhouseId', hidden: true},//仓库
            {field: 'goodsId',title:'goodsId', width: 100, hidden: true},
            {field: 'tticarSkuId',title:'skusId', width: 100, hidden: true},//规格id
            {field: 'skuId',title:'invSkuId', width: 100, hidden: true},//关联的仓储sku
            {field: 'picUrl', title: '商品图片', width: 150, formatter: function (value, row, index) {
                if (value != null && value != '') {
                    var imageSrc = 'http://tticar-test.oss-cn-shanghai.aliyuncs.com/' + value;
                    return '<div><img  style="height: 50px;width: 140px;"  src="' + imageSrc + '"></div>'
                }
            }},
            {field: 'goodsName', title: '商品名称', width: 150},
            {field: 'standardName', title: '规格', width: 100},
            {field: 'count', title: '订单数量', width: 100},
            {field: 'relativeStatus', title: '关联仓储存货', width: 180,formatter:function (value, row) {
                if (value == 0) {
                    var str = row.goodsId.substring(0,10) ;
                    str = str+"";
                    var str1 ="1"+ row.goodsId.substring(10,row.goodsId.length);
                    var skuValue = "'" +row.tticarSkuId +"'";
                    document.getElementById("addText").innerHTML="&nbsp;&nbsp;温馨提示：未关联仓储存货的商品无法发货，点击上方↑↑去关联↑↑仓储存货";
                    // document.getElementById("sendGoods").disabled=true;

                    $("#sendGoods").attr("style","display:none;");

                    return '未关联&nbsp;&nbsp;&nbsp;' + '' +
                        '<button style="background-color: pink;border-radius:2px;color:white;border: 0px;" href="#" ' +
                        'onclick="PPurchaseDetail.relativeInv('+str+','+str1+','+skuValue+')">去关联</button>' ;
                }else if (value ==1 ) {
                    document.getElementById("addText").innerHTML="";
                    // document.getElementById("sendGoods").disabled=true;

                    $("#sendGoods").attr("style","display:block;border-radius:3px;color:white;border: 0px;background-color:#00a2d4;height: 30px;width: 70px;float: right;margin-right: 20px;");
                    return '已关联:' + row['materielName'];
                }
            }},
            {field: 'invNeedCount', title: '仓库需发数量', width: 100},
            // {
            //     field: 'house',
            //     title: '<span style="color:blue">仓库/库位/批次</span>',
            //     width: 200,
            //     editor: {type: 'house'},
            //     formatter: function (value, row, index) {
            //         if (value == null || value=='') {
            //             return "";
            //         }
            //         var arr = value.split(",");
            //         var result = "";
            //         var first = "";
            //         for (var i = 0; i < arr.length; i++) {
            //             var arr2 = arr[i].split("_");
            //             result += arr2[1] + " " + arr2[3] + " " + arr2[4] + " X " + arr2[6] + "\n"
            //             if (first == "") {
            //                 first += arr2[1] + " " + arr2[3] + " " + arr2[4] + " X " + arr2[6];
            //             }
            //         }
            //         return "<a style='color:purple' title='" + result + "'>" + first + (arr.length > 1 ? "..." : "") + "</a>";
            //     }
            // },
            // {field: 'price', title: '成交单价', width: 80},


            // {field: 'fee', title: '运费', width: 80},

        ]],
        onClickCell: function (index, field) {
            if (PPurchaseDetail.editIndex != index) {
                if (PPurchaseDetail.editIndex > -1) {
                    PPurchaseDetail.dtable.datagrid('endEdit', PPurchaseDetail.editIndex);
                }
                PPurchaseDetail.editIndex = index;
            }
            if (field == "house") {
                PPurchaseDetail.dtable.datagrid('beginEdit', index);
            }
        }
    });
    PPurchaseDetail.dtable.datagrid('enableCellEditing');
};


//关联存货
PPurchaseDetail.relativeInv = function (str,str1,skuValue) {

    var str2 = str1+"";
    str2 = str2.substring(1, str2.length);
    var goodsId = str+""+str2;
    $yd.win.create('商品', "/mMateriel/searchDgNew?goodsId="+goodsId+"&skuValue="+skuValue).open(function (that, $win) {
        }
        , function (that, $win) {
            var goodsId = $("#orderCode").val();
            var order = $("#order").val();
            var id = $("#id").val();
            var data = Goods.getChecked();
            $("#data").val(data[0].skuId)
            $yd.form.create($win.find('form')).url(PPurchaseDetail.uRelative,{goodsId:goodsId,order:order,id:id,data:data}).submit(function () {
                that.close();
                PPurchaseDetail.refresh();
            });
        })
};
PPurchaseDetail.refresh = function () {
    PPurchaseDetail.dtable.datagrid('reload');
};
$(function () {

    PPurchaseDetail.orderCode = $("#orderCode").val();

    PPurchaseDetail.dtable = $('#pPurchaseDetail_table');

    PPurchaseDetail.dg(); // 采购详情数据表格


    $("input[name='payType']").combobox({
        url: "/sysDict/pay_type",
        panelHeight:'auto',
        editable:false,
        required:true,
        valueField:'id',
        textField:'text',
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });
});
PPurchaseDetail.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};

var btn2 = document.getElementById("sendGoods");
btn2.addEventListener("click", function() {
    if (PPurchaseDetail.editIndex != undefined && PPurchaseDetail.editIndex != -1) {
        PPurchaseDetail.dtable.datagrid('endEdit', PPurchaseDetail.editIndex);
    }
    var rows = PPurchaseDetail.dtable.datagrid('getRows');


    $('#submitForm').form('submit', {
        url: PPurchaseDetail.uDelivery,
        onSubmit: function () {
            // for (var i = 0; i < rows.length; i++) {
            //     var row = rows[i];
            //
            //     // console.log(row.house)
            //     if(!PPurchaseDetail.isEmpty(row.house)){
            //         var arr = row.house.split(",");
            //         var num = 0
            //         for (var j = 0; j<arr.length;j++) {
            //             num = num + arr[j][arr[j].length-1]
            //         }
            //      
            //         if (num < row.invNeedCount) {
            //             $yd.alert("第" + (i + 1) + "行,所选库存总和小于订单数量，无法完成发货");
            //             return false;
            //         }
            //     }
            //
            //     if (row.relativeStatus == 1 && PPurchaseDetail.isEmpty(row.house)) {
            //         $yd.alert("第" + (i + 1) + "行商品库存不足");
            //         return false;
            //     }
            // }

            $("#rows").val(JSON.stringify(rows));
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }else {
                $yd.alert(d.message)
            }
        }
    });
});